package br.com.viamais.filter;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

import br.com.viamais.util.MessageBundleUtil;

/**
 * Class to manager user login and permissions.
 * TODO: Logger
 * @author Eduardo
 */
public class AuthorizationListener implements PhaseListener {

	/**
	 * Serial VersionID.
	 */
	private static final long serialVersionUID = -4947344152017990445L;
	/**
	 * Session attribute name.
	 */
	private static final String USER_SESSION_ATTRIBUTE = MessageBundleUtil.getValue("configuration.session.attribute.user");

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void afterPhase(PhaseEvent event) {
		FacesContext facesContext = event.getFacesContext();
		String currentPage = facesContext.getViewRoot().getViewId();

		boolean isLoginPage = (currentPage.lastIndexOf("index.xhtml") > -1);
		HttpSession session = (HttpSession) facesContext.getExternalContext()
				.getSession(true);
		Object currentUser = session.getAttribute(USER_SESSION_ATTRIBUTE);

		if (!isLoginPage && currentUser == null) {
			NavigationHandler handler = facesContext.getApplication()
					.getNavigationHandler();
			handler.handleNavigation(facesContext, null, "loginPage");
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void beforePhase(PhaseEvent event) {
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public PhaseId getPhaseId() {
		return PhaseId.RESTORE_VIEW;
	}

}